package com.rickpan.controller;

import com.rickpan.common.ApiResponse;
import com.rickpan.entity.PaymentOrder;
import com.rickpan.service.AlipayService;
import com.rickpan.service.PaymentService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 支付相关控制器
 */
@RestController
@RequestMapping("/api/payment")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "支付系统", description = "支付相关接口")
public class PaymentController {

    private final AlipayService alipayService;
    private final PaymentService paymentService;

    /**
     * 创建支付宝支付
     */
    @PostMapping("/alipay/create/{orderNo}")
    @Operation(summary = "创建支付宝支付", description = "为指定订单创建支付宝支付链接")
    public ApiResponse<String> createAlipayPayment(@PathVariable String orderNo) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 验证订单
        PaymentOrder order = paymentService.getOrderByOrderNo(orderNo)
            .orElseThrow(() -> new RuntimeException("订单不存在"));
            
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权限操作此订单");
        }
        
        if (order.getStatus() != PaymentOrder.PaymentStatus.PENDING) {
            throw new RuntimeException("订单状态不允许支付");
        }

        try {
            String paymentForm = alipayService.createPayment(order);
            return ApiResponse.success(paymentForm);
        } catch (Exception e) {
            log.error("创建支付宝支付失败: orderNo={}", orderNo, e);
            return ApiResponse.error("创建支付失败: " + e.getMessage());
        }
    }

    /**
     * 支付宝同步回调 (用户完成支付后跳转)
     */
    @GetMapping("/alipay/return")
    @Operation(summary = "支付宝同步回调", description = "支付宝支付完成后的同步跳转地址")
    public ModelAndView alipayReturn(@RequestParam Map<String, String> params) {
        log.info("收到支付宝同步回调: {}", params);
        
        Map<String, String> result = alipayService.handleSyncCallback(params);
        
        ModelAndView modelAndView = new ModelAndView();
        
        if ("true".equals(result.get("success"))) {
            // 支付成功，跳转到成功页面
            modelAndView.setViewName("redirect:http://localhost:5173/pay-result?success=true&orderNo=" 
                + result.get("orderNo"));
        } else {
            // 支付失败，跳转到失败页面
            modelAndView.setViewName("redirect:http://localhost:5173/pay-result?success=false&message=" 
                + result.get("message"));
        }
        
        return modelAndView;
    }

    /**
     * 支付宝异步通知 (服务器间通信)
     */
    @PostMapping("/alipay/notify")
    @Operation(summary = "支付宝异步通知", description = "支付宝服务器异步通知接口")
    public String alipayNotify(@RequestParam Map<String, String> params) {
        log.info("收到支付宝异步通知: {}", params);
        
        try {
            boolean verified = alipayService.handleAsyncNotify(params);
            
            if (verified) {
                String orderNo = params.get("out_trade_no");
                String tradeNo = params.get("trade_no");
                String tradeStatus = params.get("trade_status");
                
                // 处理支付回调
                paymentService.handlePaymentCallback(orderNo, tradeNo, tradeStatus);
                
                return "success";
            } else {
                log.error("支付宝异步通知验证失败");
                return "fail";
            }
        } catch (Exception e) {
            log.error("处理支付宝异步通知失败", e);
            return "fail";
        }
    }

    /**
     * 获取支付宝配置信息 (前端使用)
     */
    @GetMapping("/alipay/config")
    @Operation(summary = "获取支付宝配置", description = "获取前端所需的支付宝配置信息")
    public ApiResponse<Map<String, String>> getAlipayConfig() {
        Map<String, String> config = alipayService.getAlipayConfig();
        return ApiResponse.success(config);
    }

    /**
     * 模拟支付回调处理 (仅用于开发测试)
     */
    @GetMapping("/mock/return")
    @Operation(summary = "模拟支付回调", description = "模拟支付成功的回调处理")
    public ModelAndView mockPaymentReturn(@RequestParam Map<String, String> params) {
        log.info("收到模拟支付回调: {}", params);
        
        try {
            String orderNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");
            String tradeStatus = params.get("trade_status");
            
            if (orderNo == null || tradeNo == null) {
                throw new RuntimeException("缺少必要参数");
            }
            
            // 验证订单存在
            PaymentOrder order = paymentService.getOrderByOrderNo(orderNo)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            if (order.getStatus() != PaymentOrder.PaymentStatus.PENDING) {
                log.warn("订单状态不允许支付: 当前状态={}", order.getStatus());
                return new ModelAndView("redirect:http://localhost:5173/pay-result?success=false&message=订单状态异常");
            }
            
            // 处理模拟支付成功
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                log.info("处理模拟支付成功: orderNo={}, tradeNo={}", orderNo, tradeNo);
                
                // 直接调用支付回调处理逻辑
                paymentService.handlePaymentCallback(orderNo, tradeNo, tradeStatus);
                
                // 添加成功后的额外处理
                log.info("VIP升级完成: orderNo={}", orderNo);
                
                return new ModelAndView("redirect:http://localhost:5173/pay-result?success=true&orderNo=" + orderNo + "&message=VIP升级成功");
            } else {
                return new ModelAndView("redirect:http://localhost:5173/pay-result?success=false&message=支付取消");
            }
            
        } catch (Exception e) {
            log.error("处理模拟支付回调失败", e);
            return new ModelAndView("redirect:http://localhost:5173/pay-result?success=false&message=" + e.getMessage());
        }
    }
    @GetMapping("/status/{orderNo}")
    @Operation(summary = "检查支付状态", description = "检查指定订单的支付状态")
    public ApiResponse<Map<String, Object>> checkPaymentStatus(@PathVariable String orderNo) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        PaymentOrder order = paymentService.getOrderByOrderNo(orderNo)
            .orElseThrow(() -> new RuntimeException("订单不存在"));
            
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权限查看此订单");
        }

        Map<String, Object> status = Map.of(
            "orderNo", order.getOrderNo(),
            "status", order.getStatus().name(),
            "statusDescription", order.getStatus().getDescription(),
            "amount", order.getAmount(),
            "createdAt", order.getCreatedAt(),
            "paidAt", order.getPaidAt(),
            "expiresAt", order.getExpiresAt()
        );

        return ApiResponse.success(status);
    }
}